<?php
declare(strict_types=1);

namespace WebApp\lib\db\redis;

use ServerApp\lib\core\ServerStation;
use WebApp\lib\db\AbstractTable;
use WebApp\lib\db\IDriver;

/**
 * Class Table
 * @package txz\common\third_lib\model\lib
 */
class RedisTable extends AbstractTable
{
    /**
     * @var IDriver
     */
    public $driver;

    public function __construct(RedisConfig $config, $server_name, $table_name, $pre = '', $suffix = '')
    {
        parent::__construct($server_name, $config->getDbName(), $table_name, $pre, $suffix);
        if (ServerStation::$wId !== null) {
            $this->driver = new RedisSwooleDriver($config);
        } else {
            if (defined("ENV_PHP_FPM") && ENV_PHP_FPM) {
                $this->driver = new NormalRedisDriver($config);
            } else {
                $this->driver = new NormalRedisDriver($config);
            }
        }
    }

    private function genKey($key = "") {
        $arr = [
            $this->getDbName(), $this->getTableName()
        ];
        if ($key) {
            array_push($arr, $key);
        }
        return join(":", $arr);
    }

    public function get(string $key){
        return $this->getPool()->exec(
            $this->driver->get($this->genKey($key))
        );
    }

    public function set(string $key, string $val, int $timeout=0){
        if ($timeout > 0) {
            return $this->getPool()->exec(
                $this->driver->setEx($this->genKey($key), $val, $timeout)
            );
        } else {
            return $this->getPool()->exec(
                $this->driver->set($this->genKey($key), $val)
            );
        }
    }

    public function keys(){
        $pre = $this->genKey();
        $len = strlen($pre) + 1;
        $arr = $this->getPool()->exec(
            $this->driver->keys($pre)
        );
        return array_map(function($row)use($len){
            return substr($row, $len, 100);
        }, $arr);
    }

    /**
     * @return RedisPool
     */
    public function getPool(): RedisPool
    {
        if (!$this->pool) {
            $this->pool = new RedisPool($this->driver);
        }
        return  $this->pool;
    }
}
